package com.zrgj.ctrl;




import com.github.pagehelper.PageInfo;


import com.zrgj.entity.Goods;
import com.zrgj.entity.Type;
import com.zrgj.entity.Unit;
import com.zrgj.entity.WmType;
import com.zrgj.services.GoodsServiceImpl;
import com.zrgj.vo.Export;
import com.zrgj.vo.GoodsVO;
import com.zrgj.vo.JsonResult;
import com.zrgj.vo.JsonResultPage;
import org.apache.commons.io.FileUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
public class GoodsController {
    Logger log= LoggerFactory.getLogger(GoodsController.class);

    @Resource
    private GoodsServiceImpl goodsService;

    @PostMapping("/mgr/goods")
    public JsonResult add(@RequestBody Goods goods){
        JsonResult jr=new JsonResult(0,"添加成功！");



        try {
            int num=goodsService.save(goods);
            if(num>0){
                jr.setCode(0);
                jr.setMsg("添加成功！");
            }else{
                jr.setCode(1);
                jr.setMsg("数据已存在！");
            }
        } catch (Exception throwables) {
            jr.setCode(2);
            jr.setMsg("服务器发生错误！");
            throwables.printStackTrace();
        }
        return jr;
    }

    @GetMapping("/mgr/goods/{id}")
    public JsonResult showById(@PathVariable String id){
        JsonResult jr=new JsonResult(0,"ok");
        Goods goods = new Goods();
        goods.setId(id);

        Goods goodsRes=null;
        try {

            goodsRes=goodsService.queryById(goods);
            if(goodsRes!=null) {
                jr.setData(goodsRes);
                jr.setCode(0);
                jr.setMsg("ok");
            }else{
                jr.setCode(1);
                jr.setMsg("查无此记录！");
            }
        } catch (Exception throwables) {
            jr.setCode(2);
            jr.setMsg("服务器发生错误！");
            throwables.printStackTrace();
        }
        return jr;
    }

    @PostMapping("/mgr/goodVO")
    public JsonResult query(@RequestBody Goods goods){
        JsonResult jr=new JsonResult(0,"ok");

        try {

            List list=goodsService.listVO(goods);
            jr.setData(list);
        } catch (Exception throwables) {
            jr.setCode(2);
            jr.setMsg("服务器发生错误！");
            throwables.printStackTrace();
        }
        return jr;
    }


    @GetMapping("/goodsExcel")
    public JsonResult queryExcel(@RequestBody Goods goods)throws Exception{
        JsonResult jr=new JsonResult(0,"ok");

        try {

            List list=goodsService.queryExcel(goods);
            jr.setData(list);
        } catch (Exception throwables) {
            jr.setCode(2);
            jr.setMsg("服务器发生错误！");
            throwables.printStackTrace();
        }
        return jr;
    }


    @GetMapping("/goodsType")
    public JsonResult queryType( Type type)throws Exception{
        JsonResult jr=new JsonResult(0,"ok");

        try {

            List list=goodsService.queryType(type);
            jr.setData(list);
        } catch (Exception throwables) {
            jr.setCode(2);
            jr.setMsg("服务器发生错误！");
            throwables.printStackTrace();
        }
        return jr;
    }

    @GetMapping("/goodsUnit")
    public JsonResult queryUnit( Unit unit)throws Exception{
        JsonResult jr=new JsonResult(0,"ok");

        try {

            List list=goodsService.queryUnit(unit);
            jr.setData(list);
        } catch (Exception throwables) {
            jr.setCode(2);
            jr.setMsg("服务器发生错误！");
            throwables.printStackTrace();
        }
        return jr;
    }
    @GetMapping("/goodsWmType")
    public JsonResult queryWmType( WmType wmType)throws Exception{
        JsonResult jr=new JsonResult(0,"ok");

        try {

            List list=goodsService.queryWmType(wmType);
            jr.setData(list);
        } catch (Exception throwables) {
            jr.setCode(2);
            jr.setMsg("服务器发生错误！");
            throwables.printStackTrace();
        }
        return jr;
    }

    @RequestMapping(value = "/download/{fileName}",method = RequestMethod.GET)
    public ResponseEntity<byte[]> download(@PathVariable String fileName, HttpServletRequest req)
            throws IOException {
//        ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
        // 获取文件存放的真实路径
        String uuid = UUID.randomUUID().toString().replace("-","");
        String realPath = req.getServletContext().getRealPath("/temp/"+uuid+".xls");
        List list = null;
        Goods goods = new Goods();
        try {
            list=goodsService.queryExcel(goods);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //生成表格
        Export.ex(list,realPath);

        //创建文件实例
        File file = new File(realPath);
        //修改文件名的编码格式


        //设置httpHeaders,使浏览器响应下载
        HttpHeaders headers = new HttpHeaders();
        //告诉浏览器执行下载的操作，“attachment”告诉了浏览器进行下载,下载的文件 文件名为 downloadFileName
        String fileName1 = fileName + ".xls";
        headers.setContentDispositionFormData("attachment",java.net.URLEncoder.encode(fileName1, "UTF-8"));
        //设置响应方式为二进制，以二进制流传输
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }





    @PostMapping("/mgr/goodsVO")
    public JsonResult queryPyCdName(@RequestBody GoodsVO goods){
        JsonResultPage jr=new JsonResultPage(0,"ok");

        PageInfo pi=null;
        try {

            pi=goodsService.queryPyCdName(goods);

        } catch (Exception throwables) {
            jr.setCode(2);
            jr.setMsg("服务器发生错误！");
            throwables.printStackTrace();
        }
        if (pi!=null){
            jr.setData(pi.getList());
            jr.setPageNum(goods.getPageNum());
            jr.setPageSize(goods.getPageSize());
            jr.setPages(pi.getPages());
            jr.setTotal(pi.getTotal());
        }else{
            jr.setCode(1);
            jr.setMsg("失败");
        }
        return jr;
    }


    @PostMapping("/mgr/goodss")
    public JsonResult query1(@RequestBody Goods goods){
        JsonResult jr=new JsonResult(0,"ok");

        try {

            List list=goodsService.list(goods);
            jr.setData(list);
        } catch (Exception throwables) {
            jr.setCode(2);
            jr.setMsg("服务器发生错误！");
            throwables.printStackTrace();
        }
        return jr;
    }

    @DeleteMapping("/mgr/goods/{id}")
    public JsonResult delById(@RequestBody Goods goods){
        JsonResult jr=new JsonResult(0,"ok");

        try {

            int num=goodsService.delById(goods);
            if(num>0){
                jr.setCode(0);
                jr.setMsg("删除成功！");
            }else{
                jr.setCode(1);
                jr.setMsg("删除失败！");
            }
        } catch (Exception throwables) {
            jr.setCode(2);
            jr.setMsg("服务器发生错误！");
            throwables.printStackTrace();
        }
        return jr;
    }

    @PostMapping("/deleteByIds")
    public JsonResult deleteByIds(@RequestParam(name = "ids[]") String[] ids){
        JsonResult jr=new JsonResult(0,"ok");
        try {
            goodsService.deleteByIds(ids);
            jr.setCode(0);
            jr.setMsg("删除成功！");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            jr.setCode(100000);
            jr.setMsg("发生错误！");
        }

        return jr;
    }

    @PutMapping("/mgr/goods")
    public JsonResult modifyById(@RequestBody Goods goods){
        JsonResult jr=new JsonResult(0,"添加成功！");

        try {

            int num=goodsService.modifyById(goods);
            if(num>0){
                jr.setCode(0);
                jr.setMsg("修改成功！");
            }else{
                jr.setCode(1);
                jr.setMsg("数据已存在！");
            }
        } catch (Exception throwables) {
            jr.setCode(2);
            jr.setMsg("服务器发生错误！");
            throwables.printStackTrace();
        }
        return jr;
    }

}
